package com.changge.module.system.service.core;

import com.changge.common.core.utils.IdUtil;
import com.changge.common.models.domain.system.core.UserRole;
import com.changge.common.models.dto.system.core.UserRoleDTO;
import com.changge.system.facade.service.core.IRoleService;
import com.changge.system.facade.service.core.IUserRoleService;
import com.changge.module.system.mapper.core.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 用户角色业务逻辑接口实现类
 *
 * @author zhangrongkang
 * @since 2023/3/15
 */
@Slf4j
@Service
public class UserRoleServiceImpl implements IUserRoleService {

    @Autowired
    private IdUtil idUtil;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 添加用户角色关联信息
     *
     * @param userId 用户ID
     * @return 是否添加成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setDefaultRole(Long userId) {
        UserRole userRole = UserRole.builder()
                .id(idUtil.nextId())
                .userId(userId)
                .roleId(roleService.getDefaultRoleId()).build();
        return userRoleMapper.insert(userRole) == 1;
    }

    /**
     * 更新用户角色
     *
     * @param userRoleDTO 用户角色关联数据传输对象
     * @return 是否更新成功
     */
    @Override
    public Boolean update(UserRoleDTO userRoleDTO) {
        // 更新用户角色
        return userRoleMapper.updateByUserId(userRoleDTO.getRoleId(), userRoleDTO.getUserId()) == 1;
    }

    /**
     * 通过用户ID获取角色ID
     *
     * @param ids 用户ID集合
     * @return 角色ID集合
     */
    @Override
    public List<Long> listRoleIdByUserId(List<Long> ids) {
        return userRoleMapper.listRoleIdByUserId(ids);
    }

    /**
     * 批量删除用户角色关联对象
     *
     * @param ids 用户ID
     * @return 受影响行数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteByUserIds(List<Long> ids) {
        return userRoleMapper.deleteBatchByUserIds(ids);
    }
}
